﻿<%@ Page Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" MasterPageFile="~masterurl/default.master" Language="C#" %>
<%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>

<asp:Content ID="Content1" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <script type="text/javascript" src="../Scripts/jquery-1.8.2.min.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
    <script type="text/javascript" src="/_layouts/15/sp.js"></script>
    <script type="text/javascript" src="/_layouts/15/SP.WorkflowServices.js"></script>
    <script type="text/javascript" src="/_layouts/15/SP.RequestExecutor.js"></script>
</asp:Content>

<%-- The markup in the following Content element will be placed in the TitleArea of the page --%>
<asp:Content ID="Content2" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server">
    Demo Page
</asp:Content>

<%-- The markup and script in the following Content element will be placed in the <body> of the page --%>
<asp:Content ID="Content3" ContentPlaceHolderID="PlaceHolderMain" runat="server">
    
    <script>
var hostUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
var appUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));

var context = null;
var subscriptionId = "82a2266e-3730-4b2d-8384-c3008c4b4ec4";
var web;
var wfManager;
var subscription;
var instances;

function StartWorkflow() {
    log("Adding site workflow.");

    context = SP.ClientContext.get_current();
    web = context.get_web();

    wfManager = new SP.WorkflowServices.WorkflowServicesManager.newObject(context, web);
    context.load(wfManager);

    subscription = wfManager.getWorkflowSubscriptionService().getSubscription(subscriptionId);
    context.load(subscription);

    instances = wfManager.getWorkflowInstanceService().enumerateInstancesForSite();
    context.load(instances);

    context.executeQueryAsync(initWorkflowSubScriptionService, err);
}

function initWorkflowSubScriptionService() {
    log("WF manager is received.");
    log("Workflow Subscription is received.");

    var isWorkflowRunning = false;

    if (instances.get_count() > 0) {
        for (var i = 0; i < instances.get_count() ; i++) {
            var workflowInstance = instances.getItemAtIndex(i);
            if (workflowInstance.get_workflowSubscriptionId().toString() === subscriptionId && workflowInstance.get_status() === 1) {
                isWorkflowRunning = true;
            }
        }
    }

    if (isWorkflowRunning) {
        log("Workflow is already running.");
    }
    else {
        wfManager.getWorkflowInstanceService().startWorkflow(subscription, new Object());

        context.executeQueryAsync(
            function (sender, args) {
                log("Workflow started successfully.");
            },
            err
        );
    }
}

function logError(args) {
    $("#results").append("Error: " + args.get_message() + '\n' + args.get_stackTrace());
}

function log(message) {
    $("#results").append(message).append("<br />");
}

function err(sender, args) {
    logError(args);
}

$.getScript("../data/data.js", function (data, textStatus, jqxhr) {
    if (appData) {
        log("Lists: ");
        for (var i = 0; i < appData.d.results.length; i++) {
            var r = appData.d.results[i];
            if (!r.Hidden) {
                log(r.Title);
            }
        }
    } else {
        log("No data received.");
    }
});

        function getQueryStringParameter(paramToRetrieve) {
            var params =
                document.URL.split("?")[1].split("&");
            var strParams = "";
            for (var i = 0; i < params.length; i = i + 1) {
                var singleParam = params[i].split("=");
                if (singleParam[0] == paramToRetrieve)
                    return singleParam[1];
            }
        }

    </script>

    <button id="btnStartWF" onclick="StartWorkflow(); return false;">Start WF</button>
    <fieldset>
        <legend>Log:</legend>
        <div id="results"></div>
    </fieldset>
</asp:Content>
